package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.*;
import com.leyou.item.pojo.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class GoodsService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private SpuDetailMapper spuDetailMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;
    private static final Logger logger = LoggerFactory.getLogger(GoodsService.class);

    private void sendMessage(Long id, String type) {
        // 发送消息
        try {
            this.amqpTemplate.convertAndSend("item." + type, id);
        } catch (Exception e) {
            logger.error("{}商品消息发送异常，商品id：{}", type, id, e);
        }
    }


    public PageResult<SpuBo> querySpuByPageAndSort(Integer page, Integer rows, Boolean saleable, String key) {

        PageHelper.startPage(page, rows);

        Example example = new Example(Spu.class);

        Example.Criteria criteria1 = example.createCriteria();
        Example.Criteria criteria2 = example.createCriteria();
        if (saleable != null) {

            criteria1.andEqualTo("saleable", saleable);
        }
        if (key != null) {

            criteria2.andLike("title", "%" + key + "%");
        }
        example.and(criteria2);
        Page<Spu> pageInfo = (Page<Spu>) spuMapper.selectByExample(example);

        List<SpuBo> spuBos = new ArrayList<>();


        for (Spu spu : pageInfo) {
            Category category1 = categoryMapper.selectByPrimaryKey(spu.getCid1());
            Category category2 = categoryMapper.selectByPrimaryKey(spu.getCid2());
            Category category3 = categoryMapper.selectByPrimaryKey(spu.getCid3());
            List<String> names = new ArrayList<>();
            names.add(category1.getName());
            names.add(category2.getName());
            names.add(category3.getName());
            String cname = StringUtils.join(names, "/");
            Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());
            SpuBo spuBo = new SpuBo();
            BeanUtils.copyProperties(spu, spuBo);
            spuBo.setBname(brand.getName());
            spuBo.setCname(cname);
            spuBos.add(spuBo);
        }


        return new PageResult<SpuBo>(pageInfo.getTotal(), new Long(pageInfo.getPages()), spuBos);
    }

    @Transactional
    public void saveGoods(SpuBo spuBo) {

        spuBo.setSaleable(true);
        spuBo.setValid(true);
        spuBo.setCreateTime(new Date());
        spuBo.setLastUpdateTime(spuBo.getCreateTime());

        spuMapper.insert(spuBo);
        spuBo.getSpuDetail().setSpuId(spuBo.getId());

        spuDetailMapper.insertSelective(spuBo.getSpuDetail());

        spuBo.getSkus().forEach(sku -> {
            sku.setSpuId(spuBo.getId());
            sku.setCreateTime(spuBo.getCreateTime());
            sku.setLastUpdateTime(spuBo.getCreateTime());
            skuMapper.insertSelective(sku);
            Stock stock = new Stock();
            stock.setSkuId(sku.getId());
            stock.setStock(sku.getStock());
            stockMapper.insertSelective(stock);
        });
        //发送消息
        sendMessage(spuBo.getId(), "insert");


    }

    public SpuDetail querySpuDetailById(Long spuId) {
        SpuDetail spuDetail = spuDetailMapper.selectByPrimaryKey(spuId);

        return spuDetail;

    }

    public List<Sku> querySkuBySpuId(Long spuId) {
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> skus = skuMapper.select(sku);
        skus.forEach(sku1 -> {
            Integer stock = stockMapper.selectByPrimaryKey(sku1.getId()).getStock();
            sku1.setStock(stock);
        });
        return skus;
    }

    @Transactional
    public void updateGoods(SpuBo spuBo) {
        spuBo.setLastUpdateTime(new Date());
        spuMapper.updateByPrimaryKeySelective(spuBo);

        spuDetailMapper.updateByPrimaryKeySelective(spuBo.getSpuDetail());

        List<Sku> allSkus = spuBo.getSkus();

        List<Long> allSkusIds = new ArrayList<>();

        /*allSkus.forEach(perSku->{
            allSkusIds.add(perSku.getId());
        });*/


        List<Sku> oldSkus = querySkuBySpuId(spuBo.getId());

        List<Long> ids = new ArrayList<>();

        oldSkus.forEach(sku -> {
            ids.add(sku.getId());
        });


        List<Sku> toBeDelete = new ArrayList<>();


        /*oldSkus.forEach(sku -> {

            if (!allSkusIds.contains(sku.getId())) {
                toBeDelete.add(sku);
            }

        });*/


        allSkus.forEach(perSku -> {
            allSkusIds.add(perSku.getId());
            if (perSku.getId() == null) {
                perSku.setSpuId(spuBo.getId());
                perSku.setCreateTime(new Date());
                perSku.setLastUpdateTime(perSku.getCreateTime());
                skuMapper.insertSelective(perSku);
                Stock stock = new Stock();
                stock.setSkuId(perSku.getId());
                stock.setStock(perSku.getStock());
                stockMapper.insertSelective(stock);
            } else if (ids.contains(perSku.getId())) {
                perSku.setSpuId(spuBo.getId());
                perSku.setLastUpdateTime(new Date());
                skuMapper.updateByPrimaryKeySelective(perSku);
                Stock stock = new Stock();
                stock.setSkuId(perSku.getId());
                stock.setStock(perSku.getStock());
                stockMapper.updateByPrimaryKeySelective(stock);

            }
        });
        //下架SKU
        oldSkus.forEach(sku -> {

            if (!allSkusIds.contains(sku.getId())) {
                toBeDelete.add(sku);
            }

        });

        toBeDelete.forEach(sku -> {
            sku.setSpuId(spuBo.getId());
            sku.setLastUpdateTime(new Date());
            sku.setEnable(false);
            skuMapper.updateByPrimaryKeySelective(sku);
        });
        //发送消息
        sendMessage(spuBo.getId(), "update");

    }

    public Spu querySpuById(Long id) {
        return spuMapper.selectByPrimaryKey(id);
    }


    public Sku querySkuById(Long id) {
        Sku sku = skuMapper.selectByPrimaryKey(id);
        return sku;
    }
}
